// 公共函数文件
function formatNumber(n) {
	n = n.toString()
	return n[1] ? n : '0' + n
}

const publicFunction = {

	formatTime() {
		const year = date.getFullYear()
		const month = date.getMonth() + 1
		const day = date.getDate()
		const hour = date.getHours()
		const minute = date.getMinutes()
		const second = date.getSeconds()

		return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
	},



	//取倒计时（天时分秒）
	getCountDown(datetimeTo) {
		// 计算目标与现在时间差（毫秒）
		// let datetime = datetimeTo.substring(0, 19);
		// let datetime2 = datetime.replace(/-/g, '/'); 使用‘-’，getTime()报错
		// let time1 = new Date(datetime2).getTime();
		let time2 = new Date().getTime();
		let mss = datetimeTo - time2;

		// 将时间差（毫秒）格式为：天时分秒
		let days = parseInt(mss / (1000 * 60 * 60 * 24));
		let hours = parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
		let minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60));
		let seconds = parseInt((mss % (1000 * 60)) / 1000);

		return days + "天" + hours + "时" + minutes + "分" + seconds + "秒"
	},

	/**
	 * 封装轻提示api
	 * @param {string} title 标题(最多7个汉字) 
	 * @param {string} icon 图标 系统默认success (三种 success loading none)
	 * @param {number} duration 延迟时间 
	 */
	showToast(title, icon = 'none', duration = 1500) {
		wx.showToast({
			title: title,
			icon: icon,
			duration: duration
		})
	},

	/**
	 * 检测手机号
	 * @param string mobile 手机号
	 * return false
	 * return mobile
	 */
	checkMobile(mobile) {
		const regex = /^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/;
		const mMobile = parseInt(mobile.replace(/\s+/g, ''), 10);
		if (typeof mMobile !== 'number') {
			return false;
		}
		return regex.test(mMobile);
	},

	loading() {
		wx.showLoading({
			title: '加载中',
			mask: true
		})
	},

	unLoading() {
		setTimeout(() => {
			wx.hideLoading();
		}, 1000);
	},

	/** 
	 * 时间戳转化为年 月 日 时 分 秒 
	 * number: 传入时间戳 
	 * format：返回格式，支持自定义，但参数必须与formateArr里保持一致 
	 */
	formatTimeFree(number, format) {

		var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
		var returnArr = [];

		var date = new Date(number * 1000);
		returnArr.push(date.getFullYear());
		returnArr.push(formatNumber(date.getMonth() + 1));
		returnArr.push(formatNumber(date.getDate()));

		returnArr.push(formatNumber(date.getHours()));
		returnArr.push(formatNumber(date.getMinutes()));
		returnArr.push(formatNumber(date.getSeconds()));

		for (var i in returnArr) {
			format = format.replace(formateArr[i], returnArr[i]);
		}
		return format;
	},
}

export default publicFunction;
